from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.db import models
import re
from django.contrib.auth import get_user_model

User = get_user_model()


# round函数在遇到0.5时不会进一位，而是趋向于偶数，这里自己写一个四舍五入 函数
def myround(x):
    if 10 * x % 10 == 5:
        return int(x) + 1
    else:
        return round(x)


class Option(models.Model):
    """此处保存全局所有选项，自关联分级"""
    value = models.CharField(max_length=20, verbose_name='选项名称')
    selfkey = models.ForeignKey(to='self', null=True, blank=True, on_delete=models.CASCADE)

    def __str__(self):
        return self.value

    class Meta:
        verbose_name = '选项名称'
        verbose_name_plural = verbose_name


class Tag(models.Model):
    name = models.CharField(max_length=5)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = verbose_name


class Customer(models.Model):
    A001 = models.CharField(primary_key=True, max_length=13, verbose_name='客户编号')  # 客户编号
    A002 = models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间')  # 创建时间
    F001 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, verbose_name='所属员工')

    B001 = models.CharField(max_length=30, verbose_name='客户全称')  # 基础信息 客户全称
    B002 = models.CharField(max_length=10, null=True, blank=True, verbose_name='简称')
    B003 = models.CharField(max_length=50, null=True, blank=True, verbose_name='关联公司名称')
    B004 = models.CharField(max_length=10, null=True, blank=True, verbose_name='客户类型')
    B005 = models.CharField(max_length=30, null=True, blank=True, verbose_name='客户所属行业')
    B006 = models.CharField(max_length=30, null=True, blank=True, verbose_name='客户经营地址')
    B007 = models.CharField(max_length=50, null=True, blank=True, verbose_name='客户网址')

    def __str__(self):
        return self.B001

    class Meta:
        verbose_name = '客户信息'
        verbose_name_plural = verbose_name


class Contacts(models.Model):
    A002 = models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间')  # 创建时间
    F001 = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='客户')  # 客户

    B001 = models.CharField(max_length=20, verbose_name='联系人姓名')
    B002 = models.CharField(max_length=5, null=True, blank=True, verbose_name='性别')
    B003 = models.CharField(max_length=30, null=True, blank=True, verbose_name='部门')
    B004 = models.CharField(max_length=30, null=True, blank=True, verbose_name='职务')
    B005 = models.CharField(max_length=30, null=True, blank=True, verbose_name='电话')
    B006 = models.CharField(max_length=60, null=True, blank=True, verbose_name='手机')
    B007 = models.EmailField(max_length=30, null=True, blank=True, verbose_name='电子邮件')
    B008 = models.CharField(max_length=30, null=True, blank=True, verbose_name='QQ')
    B009 = models.CharField(max_length=15, null=True, blank=True, verbose_name='生日')
    B010 = models.CharField(max_length=200, null=True, blank=True, verbose_name='备注')

    def __str__(self):
        return self.B001

    class Meta:
        verbose_name = '客户联系人'
        verbose_name_plural = verbose_name


class Supplier(models.Model):
    A001 = models.CharField(max_length=14, primary_key=True, blank=True, verbose_name='供应商编号')
    A002 = models.DateField(auto_now_add=True, null=True, blank=True, verbose_name='创建日期')
    F001 = models.CharField(max_length=10, null=True, blank=True, verbose_name='创建员工')

    B001 = models.CharField(max_length=30, verbose_name='供应商全称', unique=True)
    B002 = models.CharField(null=True, max_length=10, verbose_name='供应商简称', unique=True)
    B003 = models.CharField(max_length=60, blank=True, null=True, verbose_name='关联公司名称')
    B004 = models.CharField(max_length=30, blank=True, null=True, verbose_name='经营性质')
    B005 = models.CharField(max_length=80, blank=True, null=True, verbose_name='公司网址')
    B006 = models.CharField(max_length=50, blank=True, null=True, verbose_name='生产地址')

    B007 = models.TextField(null=True, blank=True, verbose_name='厂家介绍')
    B008 = models.IntegerField(default=0, blank=True, verbose_name='吹膜机数量')
    B009 = models.IntegerField(default=0, blank=True, verbose_name='流延机数量')
    B010 = models.IntegerField(default=0, blank=True, verbose_name='涂布机数量')
    B011 = models.CharField(max_length=10, blank=True, null=True, verbose_name='厂家等级')

    B012 = models.CharField(max_length=20, blank=True, null=True, verbose_name='最新付款账期')  # 合作约定事项 结算方式 最新付款账期
    B013 = models.CharField(max_length=20, blank=True, null=True, verbose_name='付款方式')  # 合作约定事项 结算方式 付款方式
    B014 = models.CharField(max_length=20, blank=True, null=True, verbose_name='对账期限')  # 合作约定事项 发票相关信息 对账期限
    B015 = models.CharField(max_length=20, blank=True, null=True, verbose_name='开票期限')  # 合作约定事项 发票相关信息 开票期限

    tag = models.ManyToManyField(Tag, verbose_name='标签')

    def __str__(self):
        return self.B001

    class Meta:
        verbose_name = '供应商'
        verbose_name_plural = verbose_name


class SupplierContacts(models.Model):
    A002 = models.DateTimeField(auto_now_add=True, null=True)  # 创建时间
    F001 = models.ForeignKey(Supplier, on_delete=models.CASCADE)  # 供应商代码

    B001 = models.CharField(max_length=10, null=True, verbose_name='联系人姓名')  # 联系人姓名
    B002 = models.CharField(max_length=5, null=True, verbose_name='性别')  # 性别
    B003 = models.CharField(max_length=15, null=True, verbose_name='部门')  # 部门
    B004 = models.CharField(max_length=15, null=True, verbose_name='职务')  # 职务
    B005 = models.CharField(max_length=60, null=True, verbose_name='电话')  # 座机 电话
    B006 = models.CharField(max_length=60, null=True, verbose_name='手机')  # 手机
    B007 = models.EmailField(max_length=60, null=True, verbose_name='电子邮件')  # 电子邮件
    B008 = models.CharField(max_length=30, null=True, verbose_name='QQ')  # QQ
    B009 = models.CharField(max_length=15, null=True, blank=True, verbose_name='生日')  # 生日
    B010 = models.CharField(max_length=3, default='未添加', verbose_name='微信是否添加')  # 微信是否添加
    B011 = models.CharField(max_length=100, null=True, verbose_name='运营地址')  # 运营地址
    B012 = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')  # 备注

    def __str__(self):
        return self.B001

    class Meta:
        verbose_name = '供应商联系人'
        verbose_name_plural = verbose_name


class ProductSeries(models.Model):
    name = models.CharField(max_length=10, verbose_name='系列名')
    first = models.CharField(max_length=4, blank=True, verbose_name='型号代码')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = '系列名'
        verbose_name_plural = verbose_name


class ProductName(models.Model):
    A001 = models.CharField(primary_key=True, max_length=15, verbose_name='对外型号')
    F001 = models.ForeignKey(ProductSeries, on_delete=models.SET_NULL, null=True, verbose_name='系列号')
    B001 = models.CharField(max_length=5, null=True, blank=True, verbose_name='基材')
    B002 = models.CharField(max_length=10, null=True, blank=True, verbose_name='类别')
    B003 = models.CharField(max_length=10, null=True, blank=True, verbose_name='胶系')
    B004 = models.CharField(max_length=10, null=True, blank=True, verbose_name='颜色')
    B005 = models.CharField(max_length=5, null=True, blank=True, verbose_name='结构')
    B006 = models.CharField(max_length=5, null=True, blank=True, verbose_name='厚度')
    C001 = models.FloatField(blank=True, default=0, verbose_name='粘度 下限')
    C002 = models.FloatField(blank=True, default=0, verbose_name='粘度 上限')

    def __str__(self):
        return self.A001

    def viscosity(self):
        rgx = re.compile(r'(?:(\.)|(\.\d*?[1-9]\d*?))0+(?=\b|[^0-9])')  # 正则表达式删除小数点后面的0
        return rgx.sub(r'\2', f'{(self.C002 + self.C001) / 2}±{(self.C002 - self.C001) / 2}')

    viscosity.short_description = '粘度范围'

    class Meta:
        verbose_name = '对外型号'
        verbose_name_plural = verbose_name


class ProductSource(models.Model):
    def get_option_list(self,name):
        return Option.objects.get(selfkey__value='产品资源库',value=name).option_set.values_list('value', 'value')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._meta.get_field('B001').choices = self.get_option_list('基材')
        self._meta.get_field('B002').choices = self.get_option_list('类别')
        self._meta.get_field('B003').choices = self.get_option_list('胶系')
        self._meta.get_field('B004').choices = self.get_option_list('颜色')
        self._meta.get_field('B005').choices = self.get_option_list('结构')

    A001 = models.CharField(max_length=20, primary_key=True, blank=True, verbose_name='产品料号')
    A002 = models.DateTimeField(auto_now_add=True, null=True, verbose_name='创建时间')
    F002 = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=True, verbose_name='供应商')

    D001 = models.CharField(max_length=30, null=True, unique=True, verbose_name='供应商型号')
    D002 = models.ForeignKey(ProductName, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='对外型号')

    B001 = models.CharField(max_length=10, null=True, blank=True,verbose_name='基材')
    B002 = models.CharField(max_length=10, null=True, blank=True,verbose_name='类别')
    B003 = models.CharField(max_length=10, null=True, blank=True,verbose_name='胶系')
    B004 = models.CharField(max_length=15, null=True, blank=True, verbose_name='颜色')
    B005 = models.CharField(max_length=5, null=True, blank=True,verbose_name='结构')
    B006 = models.CharField(max_length=10, null=True, blank=True, verbose_name='厚度')
    B007 = models.CharField(max_length=10, null=True, blank=True, verbose_name='母卷宽度')
    B008 = models.CharField(max_length=10, null=True, blank=True, verbose_name='母卷长度')
    B009 = models.TextField(null=True, blank=True, verbose_name='备注')

    C001 = models.FloatField(default=0, verbose_name='180°剥离力 下限')
    C002 = models.FloatField(default=0, verbose_name='180°剥离力 上限')
    C003 = models.CharField(max_length=10, null=True, verbose_name='被贴板材')
    C004 = models.CharField(max_length=5, null=True, verbose_name='防静电')
    C005 = models.CharField(max_length=10, null=True, blank=True, verbose_name='系列')

    def __str__(self):
        return self.A001

    def addId(self):
        product = ProductSource.objects.all().order_by('A001').last()
        self.A001 = 'HL' + str(int(product.A001[2:]) + 1).zfill(6)

    def get_viscosity_range(self):
        rgx = re.compile(r'(?:(\.)|(\.\d*?[1-9]\d*?))0+(?=\b|[^0-9])')  # 正则表达式删除小数点后面的0
        return rgx.sub(r'\2', f'{(self.C002 + self.C001) / 2}±{(self.C002 - self.C001) / 2}')

    get_viscosity_range.short_description = '粘度范围'

    def classify(self):
        # 如果必要信息没填全则先不添加对外型号
        for i in [self.B001, self.B002, self.B003, self.B004, self.B005, self.B006, self.C005]:
            if not i:
                return 0
        names = ProductSeries.objects.all()
        first = names.get(name=self.C005).first
        thickness = names.get(name=self.B006).first
        type = names.get(name=self.B002).first
        color = names.get(name=self.B004).first
        structure = names.get(name=self.B005).first
        anti_static = names.get(name=self.C004).first

        if self.B001 == 'PET':
            A001 = first + '-' + type + structure + color + thickness + str(
                myround((self.C001 + self.C002) / 2)) + anti_static
        else:
            A001 = first + '-' + type + color + thickness + str(myround((self.C001 + self.C002) / 2)) + anti_static

        product = ProductName.objects.filter(A001=A001)
        if not product.count():
            data = {
                'A001': A001,
                'B001': self.B001,
                'B002': self.B002,
                'B003': self.B003,
                'B004': self.B004,
                'B005': self.B005,
                'B006': self.B006,
                'C001': self.C001,
                'C002': self.C002,
                'F001': names.get(name=self.C005),
            }
            product = ProductName(**data)
            product.save()
            self.D002 = product
        else:
            self.D002 = product[0]
            # return self.save() # 在测试时快速添加对外型号，启用这句，一般情况下不使用

    class Meta:
        verbose_name = '产品资源'
        verbose_name_plural = verbose_name
